﻿using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using MesProjectWinform.Production.Common;
using MesProjectWinform.Production.Forms.WorkOrder;
using MesProjectWinform.Production.Models;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Production.Forms
{
    public partial class WorkOrderForm : DevExpress.XtraEditors.XtraForm
    {
        public WorkOrderForm()
        {
            InitializeComponent();
        }
        int PageIndex = 1; // 当前页码
        int PageSize = 10; // 每页显示的记录数
        int PageCount = 0; // 总页数
        int? Count = 0; // 总记录数
        public async Task ReInit()
        {
            var workorders = await GetStudentAsync();
            gridControl1.DataSource = workorders;

            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if(gridView!=null)
            {
                gridView.Columns.Clear();
                gridView.CellValueChanged += gridView_CellValueChanged;

                // 添加多选框列
                var checkEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
                gridControl1.RepositoryItems.Add(checkEdit);
                checkEdit.EditValueChanged += CheckEdit_EditValueChanged;
                var colSelect = gridView.Columns.AddVisible("IsSelected", "选择");
                colSelect.ColumnEdit = checkEdit;
                colSelect.OptionsColumn.AllowEdit = true;   // 强制可编辑
                colSelect.OptionsColumn.ReadOnly = false;   // 强制非只读
                colSelect.VisibleIndex = 0;
                colSelect.Width = 40;
                checkEdit.NullStyle = DevExpress.XtraEditors.Controls.StyleIndeterminate.Unchecked;

                // 自定义列：只显示你想要的字段，并自定义表头
                gridView.Columns.AddVisible("WORKORDERCODE", "编码"); // 添加工单编码列
                gridView.Columns.AddVisible("WORKORDERTYPEID", "类型"); // 添加工单类型列
                gridView.Columns.AddVisible("WORKCUSTOMER", "客户"); // 添加客户列
                gridView.Columns.AddVisible("PRODUCTMASTERDATANAME", "产品主数据"); // 添加产品主数据列
                gridView.Columns.AddVisible("PRODUCTIONLINENAME", "产线"); // 添加产线列
                gridView.Columns.AddVisible("WORKORDERSTATUS", "状态"); // 添加状态列
                gridView.Columns.AddVisible("PROCESSPROGRESS", "工序进度"); // 添加工序进度列
                gridView.Columns.AddVisible("WORKORDERNUM", "数量"); // 添加数量列
                gridView.Columns.AddVisible("COMPLETEDNUM", "已完成数量"); // 添加已完成数量列
                gridView.Columns.AddVisible("PROGRESS", "进度"); 
                gridView.Columns.AddVisible("TIME", "计划起止时间"); 
                gridView.Columns.AddVisible("ACTUALSTARTTIME", "实际开始时间"); 
                gridView.Columns.AddVisible("ACTUALENDTIME", "实际结束时间"); 
                gridView.Columns.AddVisible("QUANTITYNUM", "投入数量"); 
                gridView.Columns.AddVisible("GOODNUM", "良品数量"); 
                gridView.Columns.AddVisible("FAILNUM", "报废数量"); 
                gridView.Columns.AddVisible("SOURCE", "来源"); 
                gridView.Columns.AddVisible("TICKETNUMBER", "源工单号"); 
                gridView.Columns.AddVisible("WORKORDERREMARK", "备注"); 
                gridView.Columns.AddVisible("CREATEBY", "创建人"); 
                gridView.Columns.AddVisible("CREATETIME", "创建时间"); 
                gridView.Columns.AddVisible("UPDATETIME", "更新时间"); 

                if (gridView.Columns["操作"]==null)
                {
                    var col = gridView.Columns.AddVisible("操作", "操作");
                    col.UnboundType = DevExpress.Data.UnboundColumnType.Object;
                    col.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                    RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                    buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor;
                    buttonEdit.Buttons.Clear();
                    // 添加“删除”按钮
                    buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph) // 创建一个新的按钮，类型为Glyph（图标按钮）
                    {
                        Caption = "删除", // 按钮上显示的文字为“删除”
                        Kind = ButtonPredefines.Glyph, // 按钮类型为Glyph
                        // 可选：设置按钮图片为 null，仅显示文字
                        ImageOptions = { Image = null } // 不显示图片，只显示文字
                    });


                    

                    // 添加“下发”按钮
                    buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Glyph) // 创建一个新的按钮，类型为Glyph（图标按钮）
                    {
                        Caption = "下发", // 按钮上显示的文字为“下发”
                        Kind = ButtonPredefines.Glyph, // 按钮类型为Glyph
                        // 可选：设置按钮图片为 null，仅显示文字
                        ImageOptions = { Image = null } // 不显示图片，只显示文字
                    });
                    buttonEdit.ButtonClick += async (s, e) =>
                    {
                        // 获取当前主视图为GridView类型
                        var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                        // 获取当前聚焦的行句柄（索引）
                        var rowHandle = view.FocusedRowHandle;
                        // 根据行句柄获取该行的数据对象，并强制转换为WORKORDERMODEL类型
                        var row = view.GetRow(rowHandle) as WORKORDERMODEL;
                        if (row != null)
                        {
                            if (e.Button.Index == 0) // 删除按钮
                            {
                                long id = row.WORKORDERID;
                                DeleteWorkOrderById(id);
                            }
                            
                            else if(e.Button.Index==1)
                            {
                                using(var client = new HttpClient())
                                {
                                    var response = await client.PostAsync($"http://47.110.243.157:5238/api/WorkOrder/StartWorkOrder?WorkOrderCode={row.WORKORDERCODE}",null);
                                    if (response.IsSuccessStatusCode)
                                    {
                                        MessageBox.Show("下发成功");
                                        await ReInit();
                                    }
                                    else
                                    {
                                        MessageBox.Show("下发失败");
                                    }
                                }
                            }
                        }
                    };
                    col.ColumnEdit = buttonEdit;
                }
            }
        }

        private void gridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "IsSelected")
            {
                var rowData = gridView1.GetRow(e.RowHandle);
                // 你的业务逻辑
                var list = gridControl1.DataSource as List<WORKORDERMODEL>;
                if (list == null) return;

                var selected = list.Where(x => x.IsSelected).ToList();
                if (selected.Count >= 2)
                {
                    simpleButton2.Enabled = false;
                }
                else
                {
                    simpleButton2.Enabled = true;
                }
            }
        }

        private void CheckEdit_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.PostEditor();         // 立即提交编辑
            gridView1.UpdateCurrentRow();   // 更新当前行
        }

        private async void DeleteWorkOrderById(long id)
        {
            using (var client = new HttpClient()) // 创建HttpClient实例
            {
                var response = await client.DeleteAsync($"http://47.110.243.157:5238/api/WorkOrder/DeleteWorkOrder?id={id}"); // 发送删除请求
                if (response.IsSuccessStatusCode) // 判断是否删除成功
                {
                    MessageBox.Show("删除成功！"); // 弹出成功提示
                    await ReInit(); // 重新加载数据
                }
                else
                {
                    MessageBox.Show("删除失败：" + response.ReasonPhrase); // 弹出失败提示
                }
            }
        }

        private async void WorkOrderForm_Load(object sender, EventArgs e)
        {
            // 假设有 gridView1 和常用按钮 simpleButton1, simpleButton2, simpleButton3
            // 表格美化（如有gridView1）
            var gridControl = this.Controls.Find("gridControl1", true).FirstOrDefault() as DevExpress.XtraGrid.GridControl;
            var gridView1 = gridControl?.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView1 != null)
            {
                gridView1.OptionsView.EnableAppearanceEvenRow = true;
                gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(245, 249, 255);
                gridView1.Appearance.HeaderPanel.Font = new Font("微软雅黑", 11, FontStyle.Bold);
                gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gridView1.Appearance.Row.Font = new Font("微软雅黑", 10);
                gridView1.OptionsView.ShowGroupPanel = false;
                // 只对非复选框列设置只读
                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
                {
                    if (col.FieldName != "IsSelected" && col.FieldName != "选择")
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.OptionsColumn.ReadOnly = true;
                    }
                    else
                    {
                        col.OptionsColumn.AllowEdit = true;
                        col.OptionsColumn.ReadOnly = false;
                    }
                }
                gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
                gridView1.OptionsSelection.EnableAppearanceFocusedRow = true;
                gridView1.Appearance.FocusedRow.BackColor = Color.FromArgb(200, 230, 255);
                gridView1.Appearance.FocusedRow.ForeColor = Color.Black;
                gridView1.Appearance.SelectedRow.BackColor = Color.FromArgb(0, 120, 215);
                gridView1.Appearance.SelectedRow.ForeColor = Color.White;
                gridView1.Appearance.Row.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
                gridView1.RowHeight = 32;
                gridView1.Appearance.Row.BackColor = Color.White;
                gridView1.Appearance.Row.BorderColor = Color.FromArgb(230, 230, 230);
                gridView1.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.False;
                gridView1.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.False;
                gridView1.OptionsView.ShowIndicator = false;
            }
            // 按钮美化（如有）
            foreach (var btnName in new[] { "simpleButton1", "simpleButton2", "simpleButton3" })
            {
                var btn = this.Controls.Find(btnName, true).FirstOrDefault() as DevExpress.XtraEditors.SimpleButton;
                if (btn != null)
                {
                    btn.Appearance.Font = new Font("微软雅黑", 10, FontStyle.Bold);
                    btn.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.UltraFlat;
                    btn.Appearance.BackColor = Color.FromArgb(240, 240, 240);
                    btn.Appearance.ForeColor = Color.Black;
                }
            }
            await ReInit();
        }

        public async Task<List<WORKORDERMODEL>> GetStudentAsync()
        {
            using(var client = new HttpClient())
            {
                var response = await client.GetStringAsync($"http://47.110.243.157:5238/api/WorkOrder/GetWorkOrders?PageIndex={PageIndex}&PageSize={PageSize}");
                var result = JsonConvert.DeserializeObject<ApiResult<List<WORKORDERMODEL>>>(response);
                return result.Data;
            }
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            AddWorkOrderForm form = new AddWorkOrderForm();
            var result = form.ShowDialog();
            if(result==DialogResult.OK)
            {
                await ReInit();
            }
        }

        private async void BackButton_Click(object sender, EventArgs e)
        {
            if(PageIndex <= 1)
            {
                MessageBox.Show("已经是第一页了！");
                return;
            }
            PageIndex -= 1; // 返回上一页
            await ReInit();
        }

        private async void NextButton_Click(object sender, EventArgs e)
        {
            if(PageIndex >= PageCount)
            {
                MessageBox.Show("已经是最后一页了！");
                return;
            }
            PageIndex += 1; // 前往下一页
            await ReInit(); // 等待异步方法完成
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            var list = gridControl1.DataSource as List<WORKORDERMODEL>;
            if (list == null) return;

            var selected = list.Where(x => x.IsSelected).ToList();
            if (selected.Count == 0)
            {
                MessageBox.Show("请至少勾选一条记录！");
                return;
            }
            string code = selected[0].WORKORDERCODE;
            int num = (int)selected[0].WORKORDERNUM;
            object productionlineid = selected[0].PRODUCTIONLINEID;
            SplitForm form = new SplitForm();
            form.Text = $"工单拆分-{code}";
            form.GetData(code,num, productionlineid); // 将工单编码、数量和产线ID传递给拆分工单窗口
            form.MyDelegateCallback = () => WorkOrderForm_Load(null,null);
            form.ShowDialog(); // 显示拆分工单窗口
        }
    }
}